package teleinfo

import (
	"crypto/md5"
	"encoding/hex"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type config struct {
	api       string
	appKey    string
	appSecret string
}

func sign(key, secret, timeStr string) string {
	h := md5.New()
	h.Write([]byte(key + timeStr + secret))
	return hex.EncodeToString(h.Sum(nil))
}

type AuditService struct {
	config *config
}

func NewAuditService(options map[string]string) *AuditService {

	return &AuditService{
		config: &config{
			api:       options["api"],
			appKey:    options["app_key"],
			appSecret: options["app_secret"],
		},
	}

}

func (s *AuditService) getAuthParams() url.Values {

	now := time.Now()
	time := now.Format("2006-01-02 15:04:05")

	p := url.Values{}

	p.Set("app_key", s.config.appKey)
	p.Set("time", time)
	p.Set("sign", sign(p.Get("app_key"), s.config.appSecret, time))

	return p
}

// syncReport 用于提交报文
func (s *AuditService) SyncReport(report *Report) Result {

	p := s.getAuthParams()

	p.Set("command_type", report.CommandType)
	p.Set("item", report.Item)

	// 提交请求
	return s.request("POST", "/epp/message", p)
}

// request http request
func (s *AuditService) request(method, action string, post url.Values) Result {

	url := s.config.api + action

	resp, err := http.PostForm(url, post)

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()

	content, _ := ioutil.ReadAll(resp.Body)

	result := ParseResposne(content)

	return result
}
